//
//  MoyaProvider.Extension.swift
//  JLDiaryApp
//
//  Created by Jiang Chencheng on 2024/9/25.
//

import Foundation
import Moya

extension MoyaProvider {
    
    func request<T: Decodable>(_ target: Target) async throws -> T{
        
        try await withCheckedThrowingContinuation { continuation in
            
            request(target) { result in
                do {
                    let response = try result.get()
                    let value = try response.map(JLResponse<T>.self)
                    
                    if value.code > 0 {
                        continuation.resume(throwing: JLBizError.biz(message: value.message, code: value.code))
                        return
                    }
                    
                    guard let data = value.data else {
                        continuation.resume(throwing: JLBizError.notFound)
                        return
                    }
                    
                    continuation.resume(returning: data)
                   
                } catch {
                    continuation.resume(throwing: error)
                }
                
            }
            
        }
        
    }
    
    
}
